<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\CommonException;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Models\Carts;
use App\Models\CouponUsers;
use App\Models\Order;
use App\Models\Products;
use App\Models\Reservation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController
{
    /**
     * 生成預約訂單
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createReservation(Request $request)
    {
        $params=$request->all();

       $res= Reservation::create([
            'product_id'=>$params['product_id'],
            'contact_name'=>$params['contact_name'],
            'email'=>$params['email'],
            'mobile'=>$params['mobile'],
            'start_time'=>$params['start_time'],
            'users_id'=>$request->userId,
            'reservation_on'=>$this->createOrderOn()
        ]);

        $data= Reservation::with('product')->where('id',$res->id)->first();

        if($res->product_id) return $this->success($data);
        return $this->apiError('生成訂單失敗');
    }

    /**
     * 创建订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createOrder(Request $request)
    {

        $user=\request()->userId;




        if($request->input('coupon_id')){
            if(!$res= CouponUsers::where('coupon_id',$request->input('coupon_id'))->where('users_id',$user)->first()){
                return $this->apiError('該優惠券已失效！');
            }
           $coupon= $this->selectCoupon($request->input('coupon_id'),$user);
        }

        $params=$request->all();

       if($params['order_type']==1){

        if(empty($params['carts_id'])){

            $product_ids=array_column($params['product'],null,'id');

            $data=Products::select('id','name','price','num','cover_pic','integral')->whereIn('id',array_keys($product_ids))->get()->toArray();
            // if(!$data) return $this->apiError();

            foreach ($data as &$item){
                if($item['num']-$product_ids[$item['id']]['count']<0){
                    return $this->apiError($item['name'].'庫存不足');
                }
                $totalPrice[]=$product_ids[$item['id']]['count']*$item['price']; //总价格
                $item['count']=$product_ids[$item['id']]['count'];
            }

            }else{

                $data=Carts::where('status',1)->whereIn('id',explode(',',$params['carts_id']))->get()->toArray();

               if(!$data) return $this->apiError('購物車異常');
                $product=Products::select('id','name','price','num','cover_pic','integral')->whereIn('id',array_column($data,'products_id'))->get()->toArray();

                $carts=array_column($product,null,'id');

                foreach($data as &$items){

                   if( $carts[$items['products_id']]['num']-$items['num']<0){

                    return $this->apiError($carts[$items['products_id']]['name'].'庫存不足');

                   }
                   $items['id']= $items['products_id'];
                   $items['name']=$carts[$items['products_id']]['name'];
                   $items['price']=$carts[$items['products_id']]['price'];
                   $items['cover_pic']=$carts[$items['products_id']]['cover_pic'];
                   $items['integral']=$carts[$items['products_id']]['integral'];
                   $totalPrice[]=$items['num']*$carts[$items['products_id']]['price']; //总价格
                   $items['count']=$items['num'];
                   unset($items['products_id']);
                }
                Carts::destroy(explode(',',$params['carts_id']));
            }

            $address=DB::table('address')->where('id',$request->userID)->first();

                $totalPrices=array_sum($totalPrice);


           $res =Order::create([
                'order_no'=>$this->createOrderOn(),
                'pay_price'=>empty($coupon)?$totalPrices:$this->compute($coupon,$totalPrices),
                'address'=>json_encode($address),
                'product_item'=>json_encode($data),
                'users_id'=>$user,
               'order_type'=>$params['order_type'],
               'pay_mode'=>$params['pay_mode']
            ]);
           if(!empty($coupon)) CouponUsers::where('coupon_id',$request->input('coupon_id'))->where('users_id',$user)->delete();
            return $this->success(['order_id'=>$res->id]);
            // 预约订单
       }elseif($params['order_type']==2){

           $product_ids=array_column($params['product'],null,'id');
           $data=Products::select('id','name','price','num','cover_pic','integral')->whereIn('id',array_keys($product_ids))->get()->toArray();

           $res =Order::create([
               'order_no'=>$this->createOrderOn(),
               'pay_price'=>empty($coupon)?$data[0]['price']:$this->compute($coupon,$data[0]['price']),
               'time'=>$params['time'],
               'date'=>$params['date'],
               'users_id'=>$user,
               'product_item'=>json_encode($data[0]),
               'address'=>json_encode($params['address']),
               'order_type'=>$params['order_type'],
               'pay_mode'=>$params['pay_mode'],
               'products_id'=>$data[0]['id']
           ]);

            if(!empty($coupon)) CouponUsers::where('coupon_id',$request->input('coupon_id'))->where('users_id',$user)->delete();

          $goods=Products::where('id',$res->products_id)->select('id','name','price','units','cover_pic')->first();
          $order=[
              'order_id'=>$res->id,
              'time'=>$res->time,
              'date'=>$res->date,
              'order_time'=>date('Y-m-d H:i'),
              'pay_mode'=>$res->pay_mode,
              'order_no'=>$res->order_no,
              'address'=>$res->address,
              'goods'=>$goods
          ];
           return $this->success($order);
       }
    }


    /**
     * 計算折扣價
     * @param $coupon
     * @param $totalPrices
     * @return float|int
     */

    protected function compute($coupon,$totalPrices)
    {
        //满减 满折 立减 立折
        if($coupon['coupon'][0]['type']==10 && $totalPrices>$coupon['coupon'][0]['condition']){

            $moeny=  $totalPrices-$coupon['coupon'][0]['money'];
        }elseif ($coupon['coupon'][0]['type']==20 && $totalPrices>$coupon['coupon'][0]['condition']){

            $moeny=$totalPrices*sprintf('0.%s',$coupon['coupon'][0]['money']);
        }elseif ($coupon['coupon'][0]['type']==30){

            $totalPrices=$totalPrices-$coupon['coupon'][0]['money'];
        }else{
            $moeny=$totalPrices*sprintf('0.%s',$coupon['coupon'][0]['money']);
        }
        return $moeny;
    }

    /**
     * 查询是否有该优惠券
     * @param $id
     * @param $user
     * @return bool
     */
    protected function selectCoupon($id,$user)
    {

      return  CouponUsers::with('coupon')->where('coupon_id',$id)->where('users_id',$user)->first()->toArray();

    }

    /**
     * 訂單詳情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderInfo(Request $request)
    {
        $id=$request->input('id');
        if(empty($id)) return $this->apiError('訂單id不能為空');
       return $this->success(Order::where('id',$id)->first());
    }


    /**
     * 查看全部订单
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderAll()
    {
        return $this->success(Order::all());
    }

    /**
     * 確認收貨
     */
    public function affirmOrder(Request $request)
    {
        $order_id=$request->input('order_id');
        $user=$request->UserId;
        $order=Order::where('id',$order_id)->first();
        if($order->status==10) return $this->apiError('該訂單未支付');
        Order::where('id',$order_id)->update(['status'=>50]);
        return $this->success();
    }

    /**
     * 查看全部預約訂單
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getReservationAll(Request $request)
    {


      $status=$request->input('status');
      if($status==1){
         $order= Order::where('order_type',2)->where('users_id',$request->userId)->where('status',50)->orderBy('id','desc')->paginate($request->input('limit'));
      }else{
          $order= Order::where('order_type',2)->where('users_id',$request->userId)->whereIn('status',[10,20,30,40])->orderBy('id','desc')->paginate($request->input('limit'));
      }
        return $this->success($order);
    }

    /**
     * 生成订单号
     * @return string
     */
    public function createOrderOn()
    {
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}
